package cn.edu.dlmu.cogo.register;

import cn.edu.dlmu.cogo.framework.annotation.Autowired;
import cn.edu.dlmu.cogo.framework.annotation.Component;
import cn.edu.dlmu.cogo.framework.context.Environment;
import cn.hutool.core.lang.Console;

import java.util.List;

/**
 * @author hongda.li@hand-china.com 2022/3/10 21:09
 */
@Component
public class CogoRegisterCenter implements RegisterCenter {

    @Autowired
    private LocalServiceCachePool cache;

    @Override
    public boolean register(ServiceInstance instance) {
        if (cache.getServiceInstance(instance.getServiceName()) == null) {
            instance.setEnableState(true);
            instance.startInterval();
            cache.setServiceInstance(instance);
            Console.log("[CogoRegisterServer]注册中心服务端 : 服务注册成功[" + instance.getServiceName() + "]");
            return true;
        }
        Console.error("[CogoRegisterServer]注册中心服务端 : 服务注册失败[" + instance.getServiceName() + "]");
        return false;
    }

    @Override
    public ServiceInstance getService(String serviceName) {
        return cache.getServiceInstance(serviceName);
    }

    @Override
    public List<ServiceInstance> getServiceList() {
        return cache.getServices();
    }

    @Override
    public boolean enabled(String serviceName) {
        return getService(serviceName).isEnableState();
    }

    @Override
    public boolean renewService(String serviceName) {
        ServiceInstance service = getService(serviceName);
        if (service == null || !service.isEnableState()) {
            Console.error("{} [CogoRegisterServer]注册中心服务端 : 服务续约失败[{}]", Environment.getSystemTime(),serviceName);
            return false;
        }
        service.setEnableState(true);
        service.restartInterval();
        Console.log("{} [CogoRegisterServer]注册中心服务端 : 服务续约成功[{}]",Environment.getSystemTime(),serviceName);
        return true;
    }

    @Override
    public void removeService(String serviceName) {
        cache.removeServiceInstance(serviceName);
        Console.log("{} [CogoRegisterServer]注册中心服务端 : 服务下线成功[{}]",Environment.getSystemTime(),serviceName);
    }

    @Override
    public void disableService(String serviceName) {
        ServiceInstance instance = cache.getServiceInstance(serviceName);
        if (instance != null) {
            instance.setEnableState(false);
        }
    }

    @Override
    public boolean enableService(String serviceName) {
        ServiceInstance instance = cache.getServiceInstance(serviceName);
        if (instance != null) {
            instance.setEnableState(true);
            return true;
        }
        return false;
    }


}
